import axios, {AxiosError, type InternalAxiosRequestConfig, type AxiosResponse} from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";

const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    timeout: 5000,
});
request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    return config;
});
request.interceptors.response.use((config: AxiosResponse) => {
        console.log(config, '响应拦截器');
        if (config.status == 200 && config.data.code == 200) return config.data;
        config.data?.msg && ElMessage.error(config.data.msg);
        return Promise.reject();
    }, (error: AxiosError) => {
        let message = "";
        let status = error.response!.status;
        switch (status) {
            case 401:
                message = "TOKEN过期,请重新登录";
                router.push("/login")
                break;
            case 403:
                message = "无权访问";
                break;
            case 404:
                message = "请求地址错误";
                break;
            case 500:
                message = "服务器出现问题";
                break;
            default:
                message = "未知错误";
            // message = error.response!.data!.msg;
        }
        ElMessage({
            type: "error",
            message,
        });
        return Promise.reject(error);
    }
);

export default request;
